var App = getApp();
var util = require("../../utils/util")
var baseList = require('../../common/BaseList');
var basePage = require('../../common/BasePage');
Page({
  behaviors: [baseList, basePage],
  /**
   * 页面的初始数据
   */
  data: {
    bannerShow: false,
    hasInfo: true,
    isFail: false,
    search_v: '',
    screenValues: [{
        text: '最近',
        checked: false
      },
      {
        text: '折扣',
        checked: false
      },
      {
        text: '最热',
        checked: false
      },
      {
        text: '销量',
        checked: false
      },
    ],
    page: 1,
    address: '',
    userLocation: "",
    tab_page: 0,
    pop_show: true,
    shopArr: {},
    /**clschen 店铺分类 */
    tabArr:[]
  },
  stopPopEvent() {},
  changePop() {
    this.setData({
      pop_show: !this.data.pop_show
    });
  },
  showPopup() {
    this.setData({
      pop_show: false
    });
  },
  ClosePop() {
    this.setData({
      pop_show: true
    });
  },
  cleanSearch() {
    this.setData({
      search_v: ''
    })
  },
  resetScreen() {
    let arr = this.data.screenValues
    for (let item of arr) {
      item.checked = false
    };
    this.setData({
      screenValues: arr
    })
  },
  changeScreen(e) {
    // console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.resetScreen();
    this.setData({
      [`screenValues[${index}].checked`]: true,
    })
  },
  confirmScreen() {
    this.ClosePop()
    //根据选中的类型筛选商店
  },

  tabOnChange(event) {
    // console.log(event.detail.name)
    let index = event.detail.name;
    let shop_cate_id = this.data.tabArr[index].shop_cate_id;
    //获取对应商店的内容
    this.getShopList('', shop_cate_id, index)
  },
  chooseAdd() {
    wx.navigateTo({
      url: "/pages/chooseAddress/chooseAddress",
    })
  },
  getHeight(el) {
    //获取元素高度
    let query = wx.createSelectorQuery();
    query.select(el).boundingClientRect(rect => {
      let height = rect.height;
      // console.log(height);
      this.setData({
        tabHeight: height + this.data.navHeight
      })
    }).exec();
  },

  getShopCate() {
    //获取店铺分类
    util.sendRequest('shopcate/list', 'GET').then(res => {
      if (res.data.code === 0) {
        let result = res.data.result;
        this.setData({
          tabArr: result
        })
        this.getUserLocation()
        // wx.authorize({
        //   scope: 'scope.userLocation',
        //   success: (res) => {
        //     this.getUserLocation()
        //   },
        //   fail: (res) => {
        //     this.setData({
        //       noLocationAuthor: true
        //     })
        //     wx.showModal({
        //       title: '权限提示',
        //       content: '未授权定位权限,请进入设置开启定位权限',
        //       showCancel: false,
        //       confirmColor: '#ff8b9c',
        //     })
        //   }
        // })
      } else if (res.data.code === 1) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  getUserLocation() {
    // console.log('无地址信息')
    // 获取用户最近城市
    wx.getLocation({
      success: (res) => {
        this.setData({
          noLocationAuthor: false
        })
        let data = {
          latitude: res.longitude,
          altitude: res.latitude
        }
        //将坐标保存在全局
        // wx.setStorageSync('coordinate', data)
        getApp().globalData.coordinate = data
        //判断用户是否修改了城市信息：
        // if (!getApp().globalData.userLocation) {
          //没有修改信息，那么获取用户的城市
          util.sendRequest('get/recently/location', 'POST', data).then(res => {
            if (res.data.code === 0) {
              let result = res.data.result;
              // wx.setStorageSync('userLocation', result);
              getApp().globalData.userLocation = result
              this.setData({
                userLocation: result
              })
              // console.log(this.data.userLocation)
              //获取列表第一列的商店数据
              this.getShopList('', this.data.tabArr[0].shop_cate_id, 0)
              console.log('获取用户坐标成功：', getApp().globalData.coordinate);
              console.log('获取用户城市成功：', getApp().globalData.userLocation);
            } else if (res.data.code === 10) {
              wx.showToast({
                title: res.data.msg,
              })
            }
          })
        // }else{

        // }
      },
      fail: () => {
        console.log('没有定位权限权限');
        this.setData({
          noLocationAuthor: true
        })
        wx.showModal({
          title: "定位失败",
          content: 'GPS定位失败,请开启GPS定位',
          showCancel: false,
          confirmColor: '#ff8b9c',
          success(res) {
            //clschen 打开设置页面
            wx.openSetting({
              success (res) {
                console.log(res.authSetting)
       
              }
            })
          }
        })
      },
      complete: () => {}
    })
  },

  getShopList(search_word, shop_cate_id, index) {
    //判断，如果没有坐标，也就是没有定位授权信息，那么提示,不会发送请求
    if (!getApp().globalData.coordinate) {
      this.setData({
        noLocationAuthor: true
      })
      return;
    } else {
      // console.log('定位存在')
      this.setData({
        noLocationAuthor: false
      })
    }
    //初始化加载状态
    this.setData({
      [`tabArr[${index}].isLoading`]: true,
    })
    //获取店铺列表信息
    // let location = wx.getStorageSync('userLocation')
    let location = getApp().globalData.userLocation
    let data = {
      page: this.data.page,
      limit: 8,
      // //这里是测试用city_code
      city_code: location.city_code,
      // city_code: '5301',
      distance: 'asc',
      search_word,
      shop_cate_id, //商店类型
      latitude: parseFloat(getApp().globalData.coordinate.latitude),
      altitude: parseFloat(getApp().globalData.coordinate.altitude),
    }
    util.sendRequest('shop/list', 'GET', data).then(res => {
      if (res.data.code === 0) {
        let result = res.data.result.data;
        this.setData({
          [`tabArr[${index}].shopArr`]: result,
          [`tabArr[${index}].isLoading`]: false,
        })
        // console.log("shop_cate_id:", shop_cate_id)
        // console.log('index:', index)
        // console.log('result:', result)
      } else {
        //获取商店列表失败
        this.setData({
          isLoading: false,
          isFail: true
        })
      }
      console.log("获取商店列表成功:", this.data.tabArr[index].shopArr)
    })
  },

  getBanner() {
    util.sendRequest('get/bannerlist', 'GET').then(res => {
      // console.log(res)
      if (res.data.code === 0) {
        this.setData({
          bannerArr: res.data.result,
          bannerShow: true,
        })
      }
    })
  },


  onLoad: function (options) {
    this.setData({
      userLocation: wx.getStorageSync('userLocation'),
      urls: getApp().globalData.urls,
      navHeight: App.globalData.navHeight,
      hoverHeight: App.globalData.windowHeight - App.globalData.navHeight,
      navTop: App.globalData.navTop,
    })
    this.getHeight('.title_hover')
    //如果用户没有登录，会要求先进行登录，然后才要求权限
    // wx.getStorage({
    //   key: 'userInfo',
    //   fail: (res) => {
    //     wx.redirectTo({
    //       url: '/pages/accredit/accredit',
    //     })
    //   },
    //   success: (res) => {
    //     this.setData({
    //       userInfo: res.data
    //     })
    //     // this.getUserLocation()
    //     this.getShopCate()
    //   }
    // })
    
    this.getBanner()
  },

  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (getApp().globalData.userLocation) {
    //   this.setData({
    //     userLocation: getApp().globalData.userLocation
    //   })
    // }
    // console.log('当前userLocation：', getApp().globalData.userLocation)
    //clschen 每次进入首页，都应刷新列表，刷新位置
    if(this.data.tabArr&&this.data.tabArr.length>0){
      this.getUserLocation()
    }else{
      this.getShopCate()
    }
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})